<?php
/**
 * Smarty plugin
 * @category VaselinEngine
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty {captcha} function plugin
 *
 * Type:     function<br>
 * Name:     captcha<br>
 * Purpose:  print out a CAPTCHA field. Uses Zend_Captcha class
 * @author Konstantin Shamko <konstantin.shamko@gmail.com>
 * @param array parameters
 * @param Smarty
 * @return string|null
 */
function smarty_function_captcha($params, &$smarty){	
$captcha = new Zend_Captcha_Image(array(	
    'name' => $params['name'],
    'wordLen' => 6,
    'timeout' => 300,
));
$captcha->setImgDir(HOME_DIR.'tmp/captchas/');
$captcha->setImgUrl('/tmp/captchas/');
$captcha->setFont($smarty->_tpl_vars['theme'].'images/arial.ttf');
$id=$captcha->generate();
?>
<div id='captcha_<?=$params['name']?>' style='overflow:hidden;padding-bottom:10px'>
	<img src='http://<?=$_SERVER['SERVER_NAME']?>/tmp/captchas/<?=$id?>.png' class='captcha' />
    <br/>
    <input type="hidden" name='<?=$params['name']?>[id]' value='<?=$id?>'/>
    <input type="text" size="12" name='<?=$params['name']?>[input]'/> <a href="#" onclick="regenerateCaptcha<?=$params['name']?>();return false;">Try a new code</a>	

	<script type='text/javascript'>
		function regenerateCaptcha<?=$params['name']?>(){
			captcha_id = 'captcha_<?=$params['name']?>';
	
			$.ajax({
		            type: "GET",
		            url: "/default/captcha/regeneratecaptcha/name/<?=$params['name']?>",
		            dataType: "json",
		            success : pasteCaptcha<?=$params['name']?>
		     });
		} 
		
		function pasteCaptcha<?=$params['name']?>(json){
			
			$('#captcha_<?=$params['name']?>').replaceWith(json.content);
		}
	</script>
</div>
<?php
}
